/**
 *
 */
package com.naiterui.ehp.bs.patient.service.impl;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.naiterui.ehp.bp.domain.City;
import com.naiterui.ehp.bs.patient.repository.IApCityRepository;
import com.naiterui.ehp.bs.patient.service.ICityService;
import com.naiterui.ehp.bs.patient.vo.common.CityInfoVO;

@Service
public class ApCityServiceImpl implements ICityService {

    @Autowired
    private IApCityRepository cityRepository;

    @Override
    public List<CityInfoVO> getCityList(Integer pid) {
        List<City> cityList = cityRepository.findByParentIdAndAvailable(pid, true);
        /*
         * 取出第一个城市判断 查询结果的行政级别
         */
        List<CityInfoVO> cityVOList = new ArrayList<>();
        if (cityList == null || cityList.size() < 1) {
            return cityVOList;
        }
        City firstCity = cityList.get(0);
        if (firstCity.getType() == 2) {// 市
            List<City> shiCityList = new ArrayList<>();// 市级处理结果List
            City shenghui = null;
            Map<String, City> citysMap = new HashMap<>();
            for (Iterator iterator = cityList.iterator(); iterator.hasNext(); ) {
                City city = (City) iterator.next();
                if (city.getMunicipality() != null && city.getMunicipality() == 2) {// 省会
                    shenghui = city;
                    iterator.remove();
                } else {// 非省会
                    citysMap.put(city.getName(), city);
                }
            }
            if (shenghui != null) {
                shiCityList.add(shenghui);
            }
            /*
             * 按照城市首字母排序
             */
            Comparator comparator = Collator.getInstance(Locale.CHINA);
            String[] cityNameArray = citysMap.keySet().toArray(new String[citysMap.keySet().size()]);
            Arrays.sort(cityNameArray, comparator);
            for (String cityname : cityNameArray) {
                shiCityList.add(citysMap.get(cityname));
            }
            for (City city : shiCityList) {
                CityInfoVO vo = new CityInfoVO();
                BeanUtils.copyProperties(city, vo);
                cityVOList.add(vo);
            }
            return cityVOList;
        }
        for (City city : cityList) {
            CityInfoVO vo = new CityInfoVO();
            BeanUtils.copyProperties(city, vo);
            cityVOList.add(vo);
        }
        return cityVOList;
    }


}
